package com.kehutong.house.service;


import com.kehutong.common.DoveClient;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.house.entity.House;
import com.kehutong.house.entity.Shop;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@WebService("/basic/shop/service")
public class ShopService {

	static final Logger logger = LoggerFactory.getLogger(ShopService.class);

	private final static String businessType = "1103";

	@Inject
	private JdbcSession jdbcSession;

	@Inject
	private DoveClient doveClient;

	@Inject
	private BasicService basicService;

	@Inject
	private FileUrlConfig fileUrlConfig;

	@ReqMapping("/list")
	public Object list(JSONObject jsonObject) {
		return jdbcSession.findArray(Shop.class)
				.eq(jsonObject,  "shopClassifyNo","ownerMobile","ownerNo")
				.in(jsonObject, "id")
				.in(jsonObject, "communityNo")
				.like(jsonObject, "shopClassifyName", "unitName", "name", "ownerName")
                .eq("deleted", false)
				.exe();
	}

	@ReqMapping("/get")
	public Object get(Shop shop) {
		return shop;
	}

	@Bean(newInstance = true, copy = true)
	@ReqMapping("/save")
	public Object save(Shop shop) {
		jdbcSession.insert(shop);

		return shop;
	}

	@Bean(copy = true)
	@ReqMapping("/update")
	public Object update(Shop shop, JSONObject json) throws Exception {

		saveAttributeRecord(shop, json);

		jdbcSession.updateById(shop);

		return Result.success();
	}

	private void saveAttributeRecord(Shop entity, JSONObject jsonObject) throws Exception {
		if(Objects.isEmpty(entity.getOwnerNo())){
			return;
		}

		JSONObject json = new JSONObject();
		json.put("operateName", jsonObject.getString("operateName"));
		json.put("operateNo", jsonObject.getString("operateNo"));
		json.put("businessId", entity.getId());
		json.put("businessType", businessType);
		json.put("currentNo", entity.getOwnerNo());
		json.put("currentName", entity.getOwnerName());
		json.put("startTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss")));
		if(Objects.nonEmpty(entity.getOwnerNo())){
			Shop old = Pool.get(Shop.class, entity.getId());

			if(Objects.isEmpty(entity.getOwnerNo())){
				entity.setOwnerNo("");
			}

			if(Objects.isEmpty(old.getOwnerNo())){
				old.setOwnerNo("");
			}
			if(!Objects.equal(old.getOwnerNo(),entity.getOwnerNo())){
				json.put("beforeNo", old.getOwnerNo());
				json.put("beforeName", old.getOwnerName());
				JSONObject record = basicService.getAttributeRecord(json);
				if(Objects.nonEmpty(record)){
					record.put("endTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss")));
					basicService.updateAttributeRecord(record);
				}
				basicService.saveAttributeRecord(json);
			}
		}
	}

	@ReqMapping("/delete")
	public Object delete(Shop shop) throws Exception {
		shop.setDeleted(true);
		jdbcSession.updateById(shop);

		return Result.success();
	}

    @ReqMapping("/batchUpdateShopOwner")
	public Object batchUpdateShopOwner(JSONObject jsonObject){
	    List<Shop> list = jdbcSession.findArray(Shop.class)
                .eq(jsonObject,"ownerNo")
                .eq("deleted", false)
                .exe();

        list.forEach(item->{
            item.setOwnerNo(jsonObject.getString("ownerNo"));
            item.setOwnerName(jsonObject.getString("ownerName"));
            item.setOwnerMobile(jsonObject.getString("ownerMobile"));
        });

        jdbcSession.updateById(list);

        return Result.success();
    }

	@ReqMapping("/getShopInfo")
	public Object getShopInfo(JSONObject jsonObject){

		JSONArray array = jsonObject.getJSONArray("list");
		List<JSONObject> list = JSONObject.parseArray(array.toJSONString(), JSONObject.class);

		List<JSONObject> result = new ArrayList<>();
		list.forEach(json ->{
			json.put("name", json.getString("shopName"));

			Shop shop = jdbcSession.findOne(Shop.class)
					.eq(json, "name", "communityName", "shopClassifyName")
					.eq("deleted", false).exe();

			if(Objects.nonNull(shop)){
				StringBuilder builder = new StringBuilder();
				builder.append(shop.getCommunityName()).append("-")
						.append(shop.getShopClassifyName()).append("-");
				builder.append(shop.getName());

				json.put("info", builder.toString());
				json.put("id",shop.getId());
				result.add(json);
			}
		});
		return result;
	}
}
